package org.ysling.litemall.core.job;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ysling.litemall.db.domain.LitemallCoupon;
import org.ysling.litemall.db.domain.LitemallCouponUser;
import org.ysling.litemall.db.service.LitemallCouponService;
import org.ysling.litemall.db.service.LitemallCouponUserService;
import org.ysling.litemall.db.util.CouponConstant;
import org.ysling.litemall.db.util.CouponUserConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 检测优惠券过期情况
 */
@Component
public class CouponJob {
    private final Log logger = LogFactory.getLog(CouponJob.class);

    @Autowired
    private LitemallCouponService couponService;
    @Autowired
    private LitemallCouponUserService couponUserService;

    /**
     * 每隔一个小时检查
     * TODO
     * 注意，因为是相隔一个小时检查，因此导致优惠券真正超时时间可能比设定时间延迟1个小时
     */
    @Scheduled(fixedDelay = 60 * 60 * 1000)
    public void checkCouponExpired() {
        logger.info("系统开启任务检查优惠券是否已经过期");
        List<LitemallCoupon> couponList = couponService.queryExpired();
        if (!Objects.isNull(couponList) || couponList.size() > 0) {
            for (LitemallCoupon coupon : couponList) {
                coupon.setStatus(CouponConstant.STATUS_EXPIRED);
                couponService.updateById(coupon);
            }
        }

        List<LitemallCouponUser> couponUserList = couponUserService.queryExpired();
        if (!Objects.isNull(couponUserList) || couponUserList.size() > 0){
            for (LitemallCouponUser couponUser : couponUserList) {
                couponUser.setStatus(CouponUserConstant.STATUS_EXPIRED);
                couponUserService.update(couponUser);
            }
        }

        logger.info("系统结束任务检查优惠券是否已经过期");
    }

}
